package org.enhance.common.util.encryption;

import org.enhance.common.exception.EnhanceRuntimeException;
import org.enhance.common.exception.InvalidAesEncryptException;
import org.enhance.common.util.Assertion;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesUtil {

	private AesUtil() {
		throw new IllegalStateException("Constant class");
	}

	public static String encrypt(String skey, String sSrc) {
		// 判断Key是否正确
		Assertion.notEmpty(skey, "Key为空null");
		// 判断Key是否为16位
		Assertion.isTrue(skey.length() == 16, "Key长度不是16位");

		try {
			byte[] raw = skey.getBytes("utf-8");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
			byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
			return Base64.getEncoder().encodeToString(encrypted);// 此处使用BASE64做转码功能，同时能起到2次加密的作用。
		} catch (Exception e) {
			throw new EnhanceRuntimeException(e);
		}
	}

	public static String decrypt(String skey, String sSrc) {
		// 判断Key是否正确
		Assertion.notEmpty(skey, "aes.key config is null");
		// 判断Key是否为16位
		Assertion.isTrue(skey.length() == 16, "aes.key length is not 16");
		try {
			byte[] raw = skey.getBytes("utf-8");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] encrypted = Base64.getDecoder().decode(sSrc);// 先用base64解密
			byte[] original = cipher.doFinal(encrypted);
			return new String(original, "utf-8");
		} catch (Exception e) {
			throw new InvalidAesEncryptException(e);
		}
	}

}